package itbour.onetouchshow.activity.web;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.google.gson.Gson;
import com.lsjr.callback.EncryBeanCallBack;
import com.lsjr.net.RequestParams;
import com.lsjr.utils.HttpUtils;
import com.tencent.smtt.sdk.WebSettings;
import com.three.pay.PayPlatform;
import com.three.pay.ThirdPayUtils;
import com.three.pay.bean.PayInfo;
import com.three.pay.listener.PayListener;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.PaySuccessActivity;
import itbour.onetouchshow.activity.login.LoginActivity;
import itbour.onetouchshow.base.BaseWebMvpActivity;
import itbour.onetouchshow.bean.JSCallBackBean;
import itbour.onetouchshow.bean.JcmSetNavButtonBean;
import itbour.onetouchshow.bean.JsShareBean;
import itbour.onetouchshow.bean.LoginBean;
import itbour.onetouchshow.bean.PayInfoBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.EncryptUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.ThirdAppInstall;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.keyboard.IkeyBoardCallback;
import itbour.onetouchshow.utils.keyboard.KeyBoardEventBus;

import static itbour.onetouchshow.activity.version1_4.V1_4_VideoPreviewActivity.START_COMMWEBACTIVITY;

/**
 * Created by Yang on 2017/12/12.
 */

@SuppressLint("ValidFragment")
public class CommWebActivity extends BaseWebMvpActivity implements IkeyBoardCallback {

    // '/yjx/v1_0_0/user/we'
    String mtype = null;

    /*获取用户ID*/
    JSCallBackBean jsCallBackBean;


    /**
     * 获取右侧导航栏
     */
    JcmSetNavButtonBean jcmSetNavButtonBean;

    /*用户分享*/
    JsShareBean jsShareBean;

    String url = null;

    /**
     * 从js传过来的web页标题
     */
    private String webTitle;

    //页面是否初次创建
    private boolean isFirstCreate = true;
    private int switchFromState = 1;

    public void setJcmSetNavButtonBean(JcmSetNavButtonBean jcmSetNavButtonBean) {
        this.jcmSetNavButtonBean = jcmSetNavButtonBean;
    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    @Override
    protected void showTitle(String string) {
        initTitle(string);
        if (mtype.equals(AppConst.TYPE_ADDFORM)) {
            if (getWebView().canGoBack()) {
                getToolBarView().getLeftimageView().setImageResource(R.mipmap.return_icon);
            } else {
                getToolBarView().getLeftimageView().setImageResource(R.mipmap.cancle_icon);
            }
        }
        if (!TextUtils.isEmpty(webTitle)) {
            getToolBarView().setTitleText(webTitle);
        }
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        KeyBoardEventBus.getDefault().register(this);
        Bundle extras = getIntent().getExtras();
        String docId = null;
        EventBus.getDefault().register(this);
        if (extras != null) {
            mtype = extras.getString(AppConst.WEBTYPE);
            docId = extras.getString(AppConst.DOCID);
            url = extras.getString(AppConst.WEBURL);
            switchFromState = extras.getInt(AppConst.TYPE_ADDFORM_STATE, 0);
        }

        if (TextUtils.isEmpty(mtype) && TextUtils.isEmpty(url)) {
            return;
        }

        //加密请求html页面
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        RequestParams requestParams = null;
        if (mtype.equals(AppConst.TYPE_ABOUT_ME)) {
            // initTitle("用户服务协议");
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.ABOUT_ME_V1_0);
        } else if (mtype.equals(AppConst.TYPE_PAYAGREEMENT)) {
            // initTitle("支付协议");
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.PAYAGREEMENT_V1_0);
        } else if (mtype.equals(AppConst.TYPE_USERAGREEMENT)) {
            // initTitle("用户协议");
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.USERAGREEMENT_V1_0);
        } else if (mtype.equals(AppConst.TYPE_ADDFORM)) {
            // initTitle("报名表单");
            stringStringHashMap.put("userId", App.getUserId() + "");
            stringStringHashMap.put("docId", docId);
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.ADDFORM);

        } else if (mtype.equals(AppConst.TYPE_FREEBACKINFO)) {
            //initTitle("反馈信息");
            stringStringHashMap.put("userId", App.getUserId() + "");
            stringStringHashMap.put("docId", docId);
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.FREEBACKINFO);
        } else if (mtype.equals(AppConst.TYPE_WEB)) {
            //url = EncryptUtils.getPrintHtmlUrl(requestParams);
            url = extras.getString(AppConst.WEBURL);
            webTitle = extras.getString(AppConst.WEB_TITLE);
        } else if (mtype.equals(AppConst.TYPE_QA)) {
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.XIU_MI_QA);
        } else if (mtype.equals(AppConst.TYPE_VIP_AGREEMENT)) {
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.VIP_AGREEMENT);
        } else if (mtype.equals(AppConst.APP_VIP_WEB_PAY)) {
            url = extras.getString(AppConst.WEBURL);
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, url);
        } else if (mtype.equals(AppConst.COMWEB_XIUMI)) {
            stringStringHashMap.put("device", AppConst.ANDROID_DEVICE + "");
            stringStringHashMap.put("userId", App.getUserId());
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.V1_6_XMPACKAGE);
        } else if (mtype.equals(AppConst.TYPE_WEB_NEED_ENCRYPT)) {
            url = extras.getString(AppConst.WEBURL);
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, url);
        } else if (mtype.equals(AppConst.TYPE_WEB_CHALLENGE)) {
            stringStringHashMap.put("device", AppConst.ANDROID_DEVICE + "");
            stringStringHashMap.put("userId", App.getUserId());
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.MY_CHALLENGE);
        } else if (mtype.equals(AppConst.TYPE_WEB_PROFIT)) {
            stringStringHashMap.put("device", AppConst.ANDROID_DEVICE + "");
            stringStringHashMap.put("userId", App.getUserId());
            requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.MY_PROFIT);
        } else {
            finish();
        }
        if (!mtype.equals(AppConst.TYPE_WEB)) {
            url = EncryptUtils.getPrintHtmlUrl(requestParams);
        }


//        if (App.testWhendebug()) {
//            url = "http://192.168.1.250:3011/jcmTest";
//        }
        L_.e("加载的url" + url);
        initAgentWeb(url);
        CommWebJsContrl commWebJsContrl = new CommWebJsContrl(this);
        commWebJsContrl.setPayPlatformListener(new CommWebJsContrl.PayPlatformListener() {
            @Override
            public void onPayWeiXin(PayInfoBean payInfoBean) {
                weiXinPay(payInfoBean);
            }

            @Override
            public void onPayZhifuBao(PayInfoBean payInfoBean) {
                aliPay(payInfoBean);
            }
        });
        mAgentWeb.getJsInterfaceHolder().addJavaObject(AppConst.CONTRL, commWebJsContrl);
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        if (mtype.equals(AppConst.TYPE_ADDFORM)) {
            if (getWebView().canGoBack()) {
                getToolBarView().getLeftimageView().setImageResource(R.mipmap.return_icon);
            } else {
                getToolBarView().getLeftimageView().setImageResource(R.mipmap.cancle_icon);
            }
        }
        getToolBarView().getLeftimageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

//        if (mtype.equals(AppConst.COMWEB_XIUMI)) {
//            getToolBarView().setRightText("明细记录").setVisibility(View.VISIBLE);
//            getToolBarView().getRightTextView().setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    startActivity(XiuMiDetailActivity.getLaunchIntent(CommWebActivity.this,
//                            Integer.valueOf(App.getUserId())));
//                }
//            });
//
//        }
    }

    public void showRightTitle(int show, String title) {
        // T_.showToastReal("show" + show + "  title" + title);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(title)) {
                    getToolBarView().getRightTextView().setVisibility(View.GONE);
                    return;
                }
                getToolBarView().getRightImageView().setVisibility(View.GONE);
                getToolBarView().setRightText(title);
                getToolBarView().getRightTextView().setVisibility(show == 0 ? View.VISIBLE : View.GONE);
                getToolBarView().getRightTextView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (jcmSetNavButtonBean != null) {
                            String success = jcmSetNavButtonBean.getSuccess();
                            if (!TextUtils.isEmpty(success)) {
                                String call = "javascript:" + success + "()";
                                getWebView().loadUrl(call);
                            }
                        }

                    }
                });


            }
        });
    }

    public void showRightImage(int show, int content) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (content) {
                    //分享图标
                    case 1:
                        getToolBarView().getRightImageView().setImageResource(R.mipmap.icon_activity_share);
                        break;
                }
                getToolBarView().getRightTextView().setVisibility(View.GONE);
                getToolBarView().getRightImageView().setVisibility(show == 0 ? View.VISIBLE : View.GONE);
                getToolBarView().getRightImageView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (jcmSetNavButtonBean != null) {
                            String success = jcmSetNavButtonBean.getSuccess();
                            if (!TextUtils.isEmpty(success)) {
                                String call = "javascript:" + success + "()";
                                getWebView().loadUrl(call);
                            }
                        }

                    }
                });
            }
        });
    }

    protected void initTitle(String title) {
        setTitleText(title);
    }

    @Override
    public void onBackPressed() {
        if (getWebView().canGoBack()) {
            // 返回上一页面
            getWebView().getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
            getWebView().goBack();
        } else {
            if (mtype.equals(AppConst.TYPE_ADDFORM)) {
                Intent intent = new Intent();
                intent.putExtra(AppConst.TYPE_ADDFORM_STATE, switchFromState);
                setResult(START_COMMWEBACTIVITY, intent);
                finish();
            }
            super.onBackPressed();
        }

    }

    /**
     * 改变状态
     *
     * @param switchState
     */
    public void switchTypeFormState(int switchState) {
        if (switchState == 0) {
            switchFromState = 1;
        } else {
            switchFromState = 0;
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        exuJsPageStatueMethod(1, getStateType());
    }

    @Override
    protected void onResume() {
        super.onResume();
        exuJsPageStatueMethod(2, getStateType());
        String call = null;
        if (App.isLogin() && jsCallBackBean != null) {
            call = "javascript:" + jsCallBackBean.getSuccess() + "(" + App.getUserId() + ")";
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isFirstCreate = false;
        exuJsPageStatueMethod(3, getStateType());
    }

    public void onOrderPay(String orderId) {
        showProgressDialogWithText("");
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("orderId", orderId + "");
        HttpUtils.getInstance().executeGet(AppConfig.GETORDERPAYPARAM_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                dismissProgressDialog();
                L_.e(exception);
                T_.showToastReal(exception);
            }

            @Override
            protected void onSuccess(String response) {
                dismissProgressDialog();
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        PayInfoBean payInfoBean = new Gson().fromJson(response, PayInfoBean.class);
                        if (payInfoBean.getPaymentPlatform() == 10) {
                            weiXinPay(payInfoBean);
                        } else if (payInfoBean.getPaymentPlatform() == 20) {
                            aliPay(payInfoBean);
                        }
                    }
                });

                //L_.e(response);
            }
        });
    }


    public void aliPay(PayInfoBean payInfoBean) {
        PayInfo payInfo = new PayInfo();
        payInfo.setSign(payInfoBean.getAlipay().getOrderStr());
        ThirdPayUtils.initialize(CommWebActivity.this).pay(PayPlatform.AliPay, payInfo, new PayListener() {
            @Override
            public void paySuccess() {
                T_.showToastReal("支付成功");
                L_.e("支付成功");
                returnH5Success();
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        L_.i("paySuccessfinish");
                        if (mtype.equals(AppConst.COMWEB_XIUMI)) {
                            //秀米充值成功不关闭
                            if (getWebView().canGoBack()) {
                                getWebView().goBack();
                                UIUtils.getHandler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        UserMakeTag userMakeTag = UserMakeTag.REFRESH;
                                        EventBus.getDefault().post(userMakeTag);
                                        getWebView().reload();
                                        toastMessage();
                                    }
                                }, 200);
                            }
                        } else {
                            openActivity(PaySuccessActivity.class);
                            finish();
                        }

                    }
                }, 500);

            }

            @Override
            public void payFailure(Exception e) {
                T_.showToastReal("支付失败");
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                }, 500);
                // EventBus.getDefault().post(-999);
                returnH5Fail();
            }

            @Override
            public void userCancel() {
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                }, 500);
                // EventBus.getDefault().post(-999);
                returnH5Fail();
            }
        });
    }


    public void weiXinPay(PayInfoBean payInfoBean) {
        if (!ThirdAppInstall.isWeixinAvilible(getApplicationContext())) {
            T_.showCustomToast("未安装微信或微信版本过低");
            returnH5Fail();
            return;
        }
        PayInfo payInfo = new PayInfo();
        payInfo.setNonceStr(payInfoBean.getWechat().getNonceStr());
        payInfo.setPrepayId(payInfoBean.getWechat().getPrepayId());
        payInfo.setTimeStamp(payInfoBean.getWechat().getTimeStamp());
        payInfo.setSign(payInfoBean.getWechat().getSign());
        ThirdPayUtils.initialize(CommWebActivity.this).pay(PayPlatform.WxPay, payInfo, new PayListener() {
            @Override
            public void paySuccess() {
                // T_.showToastReal("支付成功");
                L_.e("支付成功");
                // EventBus.getDefault().post(1000);
                returnH5Success();
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        L_.i("paySuccessfinish");
                        if (mtype.equals(AppConst.COMWEB_XIUMI)) {
                            //秀米充值成功不关闭
                            if (getWebView().canGoBack()) {
                                getWebView().goBack();
                                UIUtils.getHandler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        UserMakeTag userMakeTag = UserMakeTag.REFRESH;
                                        EventBus.getDefault().post(userMakeTag);
                                        getWebView().reload();
                                        toastMessage();
                                    }
                                }, 200);

                            }
                        } else {
                            openActivity(PaySuccessActivity.class);
                            finish();
                        }

                    }
                }, 500);

            }

            @Override
            public void payFailure(Exception e) {
                // L_.e("支付失败");
                //T_.showToastReal("支付失败" + e.getMessage());
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                }, 500);

                // EventBus.getDefault().post(-999);
                returnH5Fail();

            }

            @Override
            public void userCancel() {
                // T_.showToastReal("取消支付");
                // L_.e("取消支付");
                //EventBus.getDefault().post(-999);
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                }, 500);
                returnH5Fail();

            }
        });
    }

    public void returnH5Fail() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String fail = jsCallBackBean.getFail();
                if (!TextUtils.isEmpty(fail)) {
                    String call = "javascript:" + fail + "()";
                    getWebView().loadUrl(call);
                }
            }
        });

    }

    public void returnH5Success() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String success = jsCallBackBean.getSuccess();
                if (!TextUtils.isEmpty(success)) {
                    String call = "javascript:" + success + "()";
                    getWebView().loadUrl(call);
                }
            }
        });

    }


    /**
     * 非wifi情况下下载耗流量提示框
     */
    public void showDialog() {
        new OneToucDialog.Builder(this)
                .content("支付未完成")
                .positiveText("重新支付").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                onOrderPay(jsCallBackBean.getOrderId() + "");
            }
        })
                .negativeText("选择放弃").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                // toastMessage();
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 99:
                    String success = data.getStringExtra(LoginActivity.successResult);
                    String result = data.getStringExtra(AppConst.USER_INFO);
                    LoginBean loginBean = new Gson().fromJson(result, LoginBean.class);
                    if (loginBean != null && loginBean.getUserInfo() != null) {
                        String call = null;
                        call = "javascript:" + success + "({userId:" + App.getUserId() + "})";
                        String finalCall = call;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                getWebView().loadUrl(finalCall);
                            }
                        });
                    }
                    break;
            }
        }

    }

    @Override
    public void dataEvent(UserMakeTag userMakeTag) {
        super.dataEvent(userMakeTag);
        if (userMakeTag.equals(UserMakeTag.BUYXIUMI)) {
            toastMessage();
        }
    }


    /**
     * 显示Vip开通成功弹框  自己消失
     */
    private void toastMessage() {
        //LayoutInflater的作用：对于一个没有被载入或者想要动态载入的界面，都需要LayoutInflater.inflate()来载入，LayoutInflater是用来找res/layout/下的xml布局文件，并且实例化
        LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater()
        View view = inflater.inflate(R.layout.custom_xiumi_toast, null); //加載layout下的布局
        RelativeLayout relativeLayout = view.findViewById(R.id.id_root_ry);
        ViewGroup.LayoutParams layoutParams = relativeLayout.getLayoutParams();
        Toast toast = new Toast(getApplicationContext());
        int width = UIUtils.WHD()[0] / 5 * 3;
        int height = width / 3 * 2;
        layoutParams.width = width;
        layoutParams.height = height;
        toast.setGravity(Gravity.CENTER, 0, 0);//setGravity用来设置Toast显示的位置，相当于xml中的android:gravity或android:layout_gravity
        // toast.setDuration(Toast.LENGTH_LONG);//setDuration方法：设置持续时间，以毫秒为单位。该方法是设置补间动画时间长度的主要方法
        toast.setView(view); //添加视图文件
        toast.show();
        /**
         *  设置背景模糊     模糊度
         */
        backgroundAlpha(0.5f);
        UIUtils.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                toast.cancel();
                backgroundAlpha(1.0f);
            }
        }, 2000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        exuJsPageStatueMethod(4, getStateType());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        exuJsPageStatueMethod(-1, getStateType());
        EventBus.getDefault().unregister(this);
        KeyBoardEventBus.getDefault().unregister(this);
    }

    private int getStateType() {
        return isFirstCreate ? 1 : 0;
    }

    private void exuJsPageStatueMethod(int status, int stateType) {
        String js = "var event = new CustomEvent('pageStateEventCallBack', {detail:{mobile_page_state_callBack:{state:" + status + ",stateType:" + stateType + "}}});document.dispatchEvent(event);";
        getWebView().evaluateJavascript(js, null);
    }

    /**
     * 回调给js
     *
     * @param status
     * @param height
     */
    private void exuJsKeyBoardStatueMethod(int status, int height) {
        String js = "var event = new CustomEvent('keyboardStateCallBack', {detail:{get_keyboard_state_callback:{state:" + status + ",height:+" + height + "}}});document.dispatchEvent(event);";
        getWebView().evaluateJavascript(js, null);
    }


    @Override
    public void onKeyBoardShow(int height) {
        //  1键盘出现，2，键盘消失
        exuJsKeyBoardStatueMethod(1, height);
    }

    @Override
    public void onKeyBoardHidden(int height) {
        //  1键盘出现，2，键盘消失
        exuJsKeyBoardStatueMethod(2, height);
    }

}
